/**
 * Created by zzh on 2022/9/30.
 */
define(function (require, exports, module) {
    "use strict";

    const zButton = require('components/button');
    const BaseLayer = require('components/layer/layer');
    const counterStore = require('store/counterStore');
    var tpl = require("./situation.html")

    module.exports = {
        template: tpl,
        components: {
            zButton: zButton,
            BaseLayer: BaseLayer
          },
        setup() {
            const counter = counterStore()
            const count = Vue.ref(0)
            return { count, counter }
        },
        data() {
            return {
                viewer: {},
                visible: true,
                val2: false,
            }
        },
        mounted() {
            this.init2();
            // var tleLine1 = '1 25544U 98067A   19156.50900463  .00003075  00000-0  59442-4 0  9992',
            //     tleLine2 = '2 25544  51.6433  59.2583 0008217  16.4489 347.6017 15.51174618173442';
            // const SampledPosition = this.getTlePositionData(tleLine1, tleLine2, this.viewer.clock.startTime, this.viewer.clock.stopTime, 1);
            // console.log(SampledPosition);

            // var endTime = new Date(currentTime.getTime() + 100 * 60 * 1000),
            // tles = [{
            //     name: 'test',
            //     tle1: '1 25544U 98067A   19156.50900463  .00003075  00000-0  59442-4 0  9992',
            //     tle2: '2 25544  51.6433  59.2583 0008217  16.4489 347.6017 15.51174618173442'
            // }]
            // var starCzml = this.tles2czml(currentTime, endTime, tles);
            // console.log(starCzml);

            // var starCzml2 = this.starOrbit(currentTime, {
            //     tle0: 'test2',
            //     tle1: '1 25544U 98067A   19156.50900463  .00003075  00000-0  59442-4 0  9992',
            //     tle2: '2 25544  51.6433  59.2583 0008217  16.4489 347.6017 15.51174618173442'
            // });
            // console.log(starCzml2);
            const baselayer = this.$refs.baselayer;
            // baselayer.updatePosition({right:50});
        },
        methods: {
            callBack(satellite, time) {
                const promise = satellite.workerTrack(time);
                if (Cesium.defined(promise)) {
                    promise.then(function (result) {
                        satellite.reloadPosition(result.cartesian, time);
                    });
                } else {
                    console.log("too many active tasks - try again later");
                }
            },
            init2() {
                var that = this;
                const sceneManager = new Situation.SceneManager('cesiumContainer', {
                    imageryProvider: new Cesium.SingleTileImageryProvider({
                        url: 'src/assets/worldimage2.jpg'
                    })
                });
                sceneManager.start();

                this.$api.tle.getBEIDOU().then(({ data }) => {
                    var tles = this.anaTle(data);

                    const satellites = [];
                    for (var i = 0; i < tles.length; i++) {
                        const star = new Situation.Satellite({
                            name: tles[i].tle0,
                            tle0: tles[i].tle0,
                            tle1: tles[i].tle1,
                            tle2: tles[i].tle2,
                            eventListener: that.callBack,
                            //referenceFrame: Cesium.ReferenceFrame.FIXED
                        })
                        satellites.push(star);
                    }
                    sceneManager.addSatellites(...satellites);
                });

            },
            init() {
                let currentTime = new Date();
                let currentTimeISOStr = currentTime.toISOString();
                var scenePacket = {
                    "id": "document",
                    "name": "situation",
                    "version": "1.0",
                    "clock": {
                        "currentTime": `${currentTimeISOStr}`,
                        "interval": "0000-00-00T00:00:00Z/9999-11-30T23:59:59Z",
                        "multiplier": 1,
                        "range": "LOOP_STOP",
                        "step": "SYSTEM_CLOCK"
                    }
                }
                this.viewer = new Cesium.Viewer('cesiumContainer', {
                    imageryProvider: new Cesium.SingleTileImageryProvider({
                        url: 'src/assets/worldimage2.jpg'
                    }),
                    geocoder: false,
                    homeButton: false,
                    sceneModePicker: false,
                    baseLayerPicker: false,
                    navigationHelpButton: false,
                    animation: false,
                    creditContainer: "credit",
                    timeline: false,
                    fullscreenButton: false,
                    vrButton: false,
                });
                this.viewer.scene.debugShowFramesPerSecond = true;

                this.$api.tle.getScenario().then(({ data }) => {
                    console.log(data);
                    var sourcePromise = Cesium.CzmlDataSource.load(data);
                    this.viewer.dataSources.add(sourcePromise);
                    this.viewer.zoomTo(sourcePromise);

                    return;
                    var tles = this.anaTle(data);
                    var czml = [];
                    czml.push(scenePacket);
                    var errTle = '';
                    for (var i = 0; i < tles.length; i++) {
                        var tle = {
                            // tle0: 'test',
                            // tle1: '1 25544U 98067A   19156.50900463  .00003075  00000-0  59442-4 0  9992',
                            // tle2: '2 25544  51.6433  59.2583 0008217  16.4489 347.6017 15.51174618173442'
                            // tle0: "0 DELTA 1 DEB (YO)",
                            // tle1: "1 00399U 62047C   18016.22580073  .00016688  00000-0  15990-3 0  9999",
                            // tle2: "2 00399  58.4006 310.4166 0006877  80.3098  65.2719 15.66862901988226",
                            tle0: "0 COSMOS 2298 DEB",
                            tle1: "1 23433U 94083C   18015.73737806 +.00000180 +00000-0 +67312-4 0  9997",
                            tle2: "2 23433 074.0072 225.9052 0011884 194.6072 292.7150 14.38707308207403"
                        }
                        var posPacket;
                        try {
                            posPacket = this.starOrbit(currentTime, tles[i]);
                        } catch (error) {
                            // errTle+=tles[i].tle0+'\r\n'+tles[i].tle1+'\r\n'+tles[i].tle2+'\r\n';
                            // console.log(error);
                            continue;
                        }
                        if ("0 FENGYUN 1C DEB" === tles[i].tle0) {
                            // console.log(tles[i]);
                        }
                        var packet = this.starInit(currentTimeISOStr, "9999-11-30T23:59:59Z", tles[i], [244, 235, 112, 255]);
                        packet['position'] = posPacket.position;
                        czml.push(packet);
                        // break;
                    }
                    // console.log(czml);
                    var sourcePromise = Cesium.CzmlDataSource.load(czml);
                    this.viewer.dataSources.add(sourcePromise);
                    this.viewer.zoomTo(sourcePromise);
                });
            },
            _read(satrec, data, gmst) {
                const positionAndVelocity = satellite.propagate(satrec, data);
                const positionEci = positionAndVelocity.position;
                if (!positionEci) {
                    console.error("获取位置错误")
                    return;
                }

                const { x, y, z } = satellite.eciToEcf(positionEci, gmst);
                const position = Cesium.Cartesian3.fromElements(
                    x * 1000,
                    y * 1000,
                    z * 1000
                );
                return position;
            },
            _setInterpolation(position) {
                const interpolationOptions = {
                    interpolationDegree: 2,
                    interpolationAlgorithm: Cesium.LagrangePolynomialApproximation
                };
                position.setInterpolationOptions(interpolationOptions);
            },
            getTlePositionData(tle1, tle2, startTime, stopTime, step = 10) {
                const SampledPosition = new Cesium.SampledPositionProperty();
                const start = new Date(startTime);
                const stop = new Date(stopTime);
                if (!tle1 || !tle2) return;
                const satrec = satellite.twoline2satrec(tle1, tle2);
                start.setTime(start.getTime() + step * 1000 * 0);
                let gmst = satellite.gstime(start);

                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                for (let i = 0; i < stop - start; i++) {
                    start.setTime(start.getTime() + step * 1000 * i);
                    gmst = satellite.gstime(start);
                    const position = this._read(satrec, start, gmst);
                    SampledPosition.addSample(Cesium.JulianDate.fromDate(start), position);
                }
                this._setInterpolation(SampledPosition);
                return SampledPosition;
            },
            tles2czml(startTime, endTime, tles) {
                // 计算起始时间和终止时间相隔的分钟数
                let minsInDuration = (endTime.getTime() - startTime.getTime()) / 60000;   //mins
                //设置为开始时间
                let initialTime = startTime.toISOString();
                //设置为结束时间
                endTime = endTime.toISOString();
                // 初始化czml数据，创建场景信息
                let tempCZML = [];
                tempCZML.push({
                    "id": "document",
                    "name": "CZML Point - Time Dynamic",
                    "version": "1.0",
                    "clock": {
                        "interval": `${initialTime}/${endTime}`,
                        "multiplier": 1,
                        "range": "LOOP_STOP",
                        "step": "SYSTEM_CLOCK"
                    }
                },
                )

                // 处理每一个sat
                for (let no = 0; no < tles.length; no++) {
                    if (!tles[no].name) {
                        console.log("请输入第" + no + 1 + "个卫星的名称");
                        return
                    };
                    if (!tles[no].tle1) {
                        console.log("请输入第" + no + 1 + "个卫星的第一个两行数");
                        return
                    };
                    if (!tles[no].tle2) {
                        console.log("请输入第" + no + 1 + "个卫星的第二个两行数");
                        return
                    };
                    let sat_name = tles[no].name;
                    // 保存位置信息
                    let res = [];
                    let satrec
                    satrec = satellite.twoline2satrec(tles[no].tle1, tles[no].tle2);
                    //satrec.no：以弧度/分钟为单位的平均运动，一天有1440分钟，一弧度是0.159155圈
                    // to go from RAD/DAY -> REV/DAY: rad * 1440 * 0.159155
                    //to go from REV/PER DAY to MINS/REV -> 1440/RevPerDay
                    let totalIntervalsInDay = satrec.no * 1440 * 0.159155; //1440 = min && 0.159155 = 1turn
                    // 获得运行一圈的分钟数
                    let minsPerInterval = 1440 / totalIntervalsInDay; // mins for 1 revolution around earth
                    // intervalTime 取起始时间 格式为2008-09-20T12:25:40.104Z
                    let intervalTime = startTime.toISOString();

                    let leadIntervalArray = [];
                    let trailIntervalArray = [];
                    // 注意：这里之所以要倒过来求leadInterval和trailInterval是因为如果正着求，很有可能在终止时刻卫星并没有运行完一圈，导致轨道只显示一半
                    for (let i = minsInDuration; i >= 0; i -= minsPerInterval) {
                        if (i <= minsPerInterval) { // intial interval 
                            let currentOrbitalInterval = {
                                "interval": `${startTime.toISOString()}/${intervalTime}`,
                                "epoch": `${startTime.toISOString()}`,
                                "number": [
                                    0, minsPerInterval * 60,
                                    minsPerInterval * 60, 0
                                ]
                            }
                            let currTrail = {
                                "interval": `${startTime.toISOString()}/${intervalTime}`,
                                "epoch": `${startTime.toISOString()}`,
                                "number": [
                                    0, 0,
                                    minsPerInterval * 60, minsPerInterval * 60
                                ]
                            }
                            leadIntervalArray.push(currentOrbitalInterval);
                            trailIntervalArray.push(currTrail);
                        }
                        else {	//not initial so make intervals 
                            let previousIntervalTime = moment(intervalTime).add(-minsPerInterval, 'm').toISOString();
                            let currentOrbitalInterval = {
                                "interval": `${previousIntervalTime}/${intervalTime}`,
                                "epoch": `${previousIntervalTime}`,
                                "number": [
                                    0, minsPerInterval * 60,
                                    minsPerInterval * 60, 0
                                ]
                            }
                            let currTrail = {
                                "interval": `${previousIntervalTime}/${intervalTime}`,
                                "epoch": `${previousIntervalTime}`,
                                "number": [
                                    0, 0,
                                    minsPerInterval * 60, minsPerInterval * 60
                                ]
                            }
                            intervalTime = moment(intervalTime).add(-minsPerInterval, 'm').toISOString();
                            leadIntervalArray.push(currentOrbitalInterval);
                            trailIntervalArray.push(currTrail);
                        }
                    }
                    // Seconds between current time and epoch time
                    let julianEpoch = new Cesium.JulianDate(satrec.jdsatepoch);
                    let epoch = Cesium.JulianDate.toDate(julianEpoch);
                    let sec = (startTime - epoch) / 1000;
                    for (let i = sec; i <= sec + minsPerInterval * 60; i += 60) { //每60秒计算一个位置信息，最后采用拉格朗日插值法处理数据
                        // 根据当前时间距tle两行数历元时刻的分钟数，计算当前卫星位置和速度
                        let positionAndVelocity = satellite.sgp4(satrec, i * 0.0166667); // 0.0166667min = 1sec
                        // 地惯坐标系
                        let positionEci = positionAndVelocity.position;
                        positionEci.x = positionEci.x * 1000;
                        positionEci.y = positionEci.y * 1000;
                        positionEci.z = positionEci.z * 1000;
                        // let velocityEci = positionAndVelocity.velocity;
                        // velocityEci.x = velocityEci.x * 1000;
                        // velocityEci.y = velocityEci.y * 1000;
                        // velocityEci.z = velocityEci.z * 1000;

                        res.push(i - sec, positionEci.x, positionEci.y, positionEci.z);
                    }
                    let initialCZMLProps =
                    {
                        "id": `${sat_name}`,
                        "name": `${sat_name}`,
                        "availability": `${initialTime}/${endTime}`,
                        "label": {
                            "fillColor": {
                                "rgba": [
                                    255, 0, 255, 255
                                ]
                            },
                            "font": "11pt Lucida Console",
                            "horizontalOrigin": "LEFT",
                            "outlineColor": {
                                "rgba": [
                                    0, 0, 0, 255
                                ]
                            },
                            "outlineWidth": 2,
                            "pixelOffset": {
                                "cartesian2": [
                                    12, 0
                                ]
                            },
                            "show": true,
                            "style": "FILL_AND_OUTLINE",
                            "text": `${sat_name}`,
                            "verticalOrigin": "CENTER"
                        },
                        "path": {
                            "show": [
                                {
                                    "interval": `${initialTime}/${endTime}`,
                                    "boolean": true
                                }
                            ],
                            //"width": 3,
                            "material": {
                                "solidColor": {
                                    "color": {
                                        "rgba": [
                                            // 随机生成轨道颜色
                                            Math.floor(255 * Math.random(0, 1)), Math.floor(255 * Math.random(0, 1)), Math.floor(255 * Math.random(0, 1)), 255
                                        ]
                                    }
                                }
                            },
                            //"resolution": 120,
                            // The time ahead of the animation time, in seconds, to show the path.
                            //"leadTime": leadIntervalArray,
                            // The time behind the animation time, in seconds, to show the
                            //"trailTime": trailIntervalArray
                        },
                        "billboard": {
                            "eyeOffset": {
                                "cartesian": [
                                    0, 0, 0
                                ]
                            },
                            "horizontalOrigin": "CENTER",
                            "image": "",
                            "pixelOffset": {
                                "cartesian2": [
                                    0, 0
                                ]
                            },
                            "scale": 1.5,
                            "show": true,
                            "verticalOrigin": "CENTER"
                        },
                        "position": {
                            // 采用拉格朗日插值法
                            "interpolationAlgorithm": "LAGRANGE",
                            // 1为线性插值，2为平方插值
                            "interpolationDegree": 2,
                            // 参考坐标系，地惯坐标系
                            "referenceFrame": "INERTIAL",
                            "epoch": `${initialTime}`,
                            "cartesian": res
                        }
                    }
                    tempCZML.push(initialCZMLProps);
                }
                return tempCZML;
            },
            starInit(start_time, end_time, tle, star_orbit_color) {
                let satrec;
                satrec = satellite.twoline2satrec(tle.tle1, tle.tle2);
                let sat_id = satrec.satnum;
                let packet = {
                    "id": `${sat_id}`,
                    "name": `${tle.tle0}`,
                    "availability": `${start_time}/${end_time}`,
                    "path": {
                        "show": [
                            {
                                "interval": `${start_time}/${end_time}`,
                                "boolean": true
                            }
                        ],
                        "material": {
                            "solidColor": {
                                "color": {
                                    "rgba": star_orbit_color
                                }
                            }
                        },
                    },
                    "point": {
                        "color": {
                            "rgbaf": new Cesium.Color(0.0, 0.35, 1.0, 1.0),
                        },
                        "outlineColor": {
                            "rgbaf": new Cesium.Color(0.0, 1.0, 1.0, 1.0),
                        },
                        "outlineWidth": 0,
                        "pixelSize": 1,
                    },
                }
                return packet;
            },
            starOrbit(startTime, tle) {
                let satrec;
                satrec = satellite.twoline2satrec(tle.tle1, tle.tle2);
                let sat_id = satrec.satnum;
                //周期，单位(秒/圈)
                let cycle = 60 / (satrec.no * 0.159155);
                //开始时间ISO字符串
                let epochStr = startTime.toISOString();
                // 保存时间位置信息
                let cartesian = [];
                let jdsatepoch = new Cesium.JulianDate(satrec.jdsatepoch);
                let tleEpoch = Cesium.JulianDate.toDate(jdsatepoch);
                let difSec = (startTime - tleEpoch) / 1000;
                let endPoit = difSec + cycle;
                let step = 300;
                try {
                    for (let i = difSec, j = i + step; i <= endPoit; j += step) {
                        let posAndVel = satellite.sgp4(satrec, i * 0.0166667);
                        // 地惯坐标系
                        let posEci = posAndVel.position;

                        posEci.x = posEci.x * 1000;
                        posEci.y = posEci.y * 1000;
                        posEci.z = posEci.z * 1000;
                        cartesian.push(i - difSec, posEci.x, posEci.y, posEci.z);
                        if (i >= endPoit) {
                            break;
                        }
                        if (j > endPoit) {
                            i = endPoit;
                        } else {
                            i = j;
                        }
                    }
                } catch (error) {
                    throw new Error(tle);
                }
                let packet =
                {
                    "id": `${sat_id}`,
                    "position": {
                        "interpolationAlgorithm": "LAGRANGE",
                        "interpolationDegree": 5,
                        "referenceFrame": "INERTIAL",
                        "epoch": `${epochStr}`,
                        "cartesian": cartesian
                    }
                }
                return packet;
            },
            anaTle(data) {
                let datas = data.split('\r\n');
                var tles = [];
                for (var i = 0; i < datas.length; i += 3) {
                    tles.push({
                        tle0: datas[i],
                        tle1: datas[i + 1],
                        tle2: datas[i + 2],
                    });
                }
                return tles;
            },
            test() {
                var that = this;
                // layer.msg('hello');
                layer.open({
                    type: 1,
                    title: 'test',
                    area: ['390px','260px'],
                    shade: 0,
                    maxmin: true,
                    offset: [
                        Math.random()*($(window).height-300),
                        Math.random()*($(window).width-390),
                    ],
                    content: '<z-button>xxxxx</z-button>',
                    btn: ['继续弹出','关闭所用'],
                    yes: function(){
                        that.test();
                    },
                    btn2: function(){
                        layer.closeAll();
                    },
                    zIndex: layer.zIndex,
                    success: function(layero,index){
                        layer.setTop(layero);
                        layer.escIndex = layer.escIndex || [];
                        layer.escIndex.unshift(index);
                        layero.on('mousedown',function(){
                            var _index = layer.escIndex.indexOf(index);
                            if(_index !== -1){
                                layer.escIndex.splice(_index,1);
                            }
                            layer.escIndex.unshift(index);
                        });
                    },
                    end: function(){
                        if(typeof layer.escIndex === 'object'){
                            layer.escIndex.splice(0,1);
                        }
                    }
                })
                that.visible = true;
            },
            trigger() {
                this.$refs.baselayer.trigger();
            },
        }
    }
})